#pragma once
#include <iostream>
#include <functional>
#include <strings.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "log.hpp"

using func_t = std::function<std::string(const std::string &)>;
const int Size = 1024;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    LISTEN_ERR,
};

static uint16_t defaultport = 8888;
static std::string defaultip = "0.0.0.0";
log lg;

class udpserver
{

public:
    udpserver(uint16_t port = defaultport, std::string ip = defaultip)
        : _port(port), _ip(ip), _sockfd(0), _isrunning(false)
    {}

    void init()
    {
        if (_isrunning == true)
            return;

        // 代表是IPV4传输协议/套接字类型/特定协议

        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 先创建套接字
        if (_sockfd == -1)
        {
            lg(Fatel, "socket create faile , sockfd is %d", _sockfd);
            exit(SOCKET_ERR);
        }

        lg(Info, "socket create success", _sockfd);

        struct sockaddr_in local;
        local.sin_family = AF_INET;                     // 传输协议
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 字符串转成4个字节的整数
        local.sin_port = htons(_port);

        if (bind(_sockfd, (const sockaddr *)&local, sizeof(local)))
        {
            lg(Fatel, "socket bind errno, errno %d, errno string is: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "socket bind success");
        // if (listen(_sockfd, 3) < 0)
        // {
        //     std::cerr << "Listen failed\n";
        //     close(_sockfd);
        //     exit(LISTEN_ERR);
        // }
    }

    void run(func_t func)
    {
        _isrunning = true;
        char inbuffer[Size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Waring, "recvfrom error,errno %d,errno string is %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            std::cout << inbuffer;
            std::string tmp = "server received message:";
            tmp += inbuffer;
            sendto(_sockfd, tmp.c_str(), tmp.size(), 0, (sockaddr *)&client, len);
        }
    }

    ~udpserver()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    bool _isrunning;
};